<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    title="新增白名单"
    width="40%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="gift-form"
    >
      <!-- 描述信息 -->
      <el-card class="mb-20">
        <el-row :gutter="10">
          <el-col>
            <el-form-item label="白名单类型" prop="type">
              <el-select
                v-model="formData.type"
                placeholder="请选择白名单类型"
                style="width: 100%"
              >
                <el-option
                  v-for="(value, key) in categoryOptions"
                  :key="key"
                  :label="value"
                  :value="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col>
            <el-form-item label="白名单ID" prop="content">
              <el-input
                v-model="formData.content"
                placeholder="请输入白名单ID"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col>
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
        >
          新增
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick, onMounted } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { getWhitelistTypeRecord, WhitelistTypeRecord } from "@/api/whitelog";

// 定义props
interface Props {
  modelValue: boolean;
  giftData?: any;
  isEdit?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  giftData: null,
  isEdit: false,
});

// 定义emits
const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  submit: [data: any];
}>();

// 表单ref
const formRef = ref<FormInstance>();

// 提交loading
const submitLoading = ref(false);

// 弹框显示状态
const visible = ref(false);

// 白名单分类选项
const categoryOptions = ref<WhitelistTypeRecord[]>([]);

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
    if (newVal) {
      nextTick(() => {
        initFormData();
      });
    }
  }
);

// 监听visible变化
watch(visible, (newVal) => {
  emit("update:modelValue", newVal);
});

// 加载封禁分类
const loadCategories = async () => {
  try {
    const response = await getWhitelistTypeRecord();
    categoryOptions.value = response.data;
  } catch (error) {
    console.error("加载封禁分类失败:", error);
  }
};

// 表单数据
const formData = reactive({
  id: "",
  type: "",
  content: "",
  remark: "",
});

// 表单验证规则
const formRules: FormRules = {
  content: [{ required: true, message: "请输入白名单ID", trigger: "blur" }],
  type: [{ required: true, message: "请选择白名单类型", trigger: "change" }],
};

// 初始化表单数据
const initFormData = () => {
  Object.assign(formData, {
    id: "",
    type: "",
    content: "",
    remark: "",
  });
};

// 关闭弹框
const handleClose = () => {
  visible.value = false;
  // 编辑时不清空ID字段
  // if (props.isEdit) {
  //   formRef.value?.clearValidate();
  // } else {
  //   formRef.value?.resetFields();
  // }
  formRef.value?.resetFields();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    console.log("开始表单验证，编辑模式:", props.isEdit);

    // 使用 Promise 方式验证表单
    const validateForm = () => {
      return new Promise((resolve, reject) => {
        // 编辑时跳过ID字段验证
        console.log("新增模式验证规则:", formRules);
        formRef.value?.validate((valid: boolean, fields: any) => {
          if (valid) {
            resolve(true);
          } else {
            reject(fields);
          }
        });
      });
    };

    await validateForm();

    console.log("表单验证通过，开始提交");
    submitLoading.value = true;

    // 构建提交数据
    const submitData = {
      ...formData,
    };

    console.log("提交数据:", submitData);

    // 触发父组件的submit事件
    emit("submit", submitData);
  } catch (error) {
    console.error("表单验证失败:", error);
    ElMessage.error("表单验证失败，请检查输入");
    return; // 验证失败时直接返回，不继续执行
  } finally {
    submitLoading.value = false;
  }
};

// 组件挂载后初始化
onMounted(() => {
  loadCategories();
});
</script>

<style lang="less" scoped>
.gift-form {
  .mb-20 {
    margin-bottom: 20px;
  }

  .card-header {
    font-weight: 500;
    color: #333;
  }

  .image-preview {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    background-color: #f5f7fa;
  }

  .animation-preview {
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    background-color: #f5f7fa;
  }

  .upload-container {
    width: 100%;
    margin-top: 10px;
  }

  .form-tip {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-top: 4px;
    font-size: 12px;
    color: #909399;

    .el-icon {
      font-size: 14px;
      color: #409eff;
    }
  }

  .content-left {
    margin-left: 15px;
  }
}

.dialog-footer {
  text-align: right;
}
</style>
